//
//  JMChangeMyBankController.m
//  NewiOSProject
//
//  Created by li on 2023/9/12.
//  Copyright © 2023 范智渊. All rights reserved.
//

#import "JMChangeMyBankController.h"

#import "LayoutView.h"

#import "JMPickerSelectionView.h"
#import "JMPickerSelectionModel.h"
#import "PaddingView.h"
#import "LayoutScrollView.h"
#import "CustomStackView.h"
#import "CustomStackView.h"
#import "LayoutView.h"
#import "UIView+PopupProtocol.h"

#import "JMAuthentiactionConfirmView.h"
#import "JMAuthenticationInputListItemView.h"
#import "JMUserBanckInfoModel.h"
#import "JMPhoneCodePopupView.h"
@interface JMChangeMyBankController ()<JMPublicAlertViewDelegate>
@property(nonatomic, strong) UIStackView *rootStack;
@property(nonatomic, strong) LayoutScrollView *scrollView;
@property(nonatomic, strong) JMAuthentiactionConfirmView *confirmView;
@property(nonatomic, strong) JMAuthenticationInputListItemView *bankCardConfirmView;

@property(nonatomic, strong) JMUserBanckInfoModel *userBanckInfoModel;
@property(nonatomic, assign) BOOL isBankCard;
@property(nonatomic, assign) BOOL isBankCardEqual;
@property(nonatomic, strong) JMPhoneCodePopupView *popupView;
@property (nonatomic, strong)JMPublicAlertView *voiceCodeAlertV;//语音验证码弹窗
@property (nonatomic, strong)NSString *telNumber;
@property (nonatomic, strong)NSString *bankName;
@property (nonatomic, strong)NSString *cardNum;
@property (nonatomic, strong)NSString *cardNumConfirm;
@property (nonatomic, strong)NSString *code;

@end

@implementation JMChangeMyBankController


-(void)backBtnClick{
    [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.telNumber = JMProjectManager.sharedJMProjectManager.loginUser.phone;

    
    self.TitleLabel.text = @"Modificar cuenta bancaria";
    [self.backBtn setImage:ImageNamed(@"ICON／zuo_black") forState:(UIControlStateNormal)];

    self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupViews];
}

- (void)setupViews {
    WeakSelf
    [self.rootStack addArrangedSubview:self.scrollView];
    [self.rootStack addArrangedSubview: [[PaddingView initWithContentView:self.confirmView edgeInsets:(UIEdgeInsetsMake(0, 16, 0, 16))] then:^(PaddingView * _Nonnull view) {
        [view.widthAnchor constraintEqualToConstant:kScreenWidth].active = YES;
    }]];
    for (NSInteger i = 0; i < 3; i ++) {
        JMAuthenticationInputListItemView *itemView = [JMAuthenticationInputListItemView new];
        [itemView.widthAnchor constraintEqualToConstant:kScreenWidth].active = YES;
//        itemView.textField.textColor = [UIColor colorWithHexString:@"#0F1511"];
        
        if (i == 0) {
            itemView.titleLab.text = @"Nombre del banco";
            itemView.textField.placeholder = @"Seleccione por favor";
            itemView.tag = 100;
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:itemView.textField];
            itemView.textField.enabled = NO;
            itemView.popupView.type = 6;
            itemView.popupView.searchPaddingView.hidden = NO;
            itemView.willShowPopupView = ^{
                [JMCommonMethod uploadStatistics:@"EditBankcard" actionType:@"Bank_Name_Focus" parameters:nil];
            };
            itemView.popupView.confirmCallback = ^(JMPickerSelectionModel * _Nullable model) {
                
                itemView.textField.text = model.label;
                weakSelf.userBanckInfoModel.bankName = model.label;
                weakSelf.userBanckInfoModel.bankCode = model.value;
                
                [weakSelf checkConfirmViewAble];
            };
        }
        else if (i == 1) {
            
            itemView.titleLab.text = @"Número de cuenta CLABE o tarjeta bancaria";
            itemView.textField.placeholder = @"Por favor escribe";
            itemView.textField.enabled = YES;
            itemView.textField.keyboardType = UIKeyboardTypeNumberPad;
            itemView.textField.clearButtonMode = UITextFieldViewModeWhileEditing;

            itemView.tag = 200;
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:itemView.textField];
            itemView.moreImage.hidden = YES;
            
            itemView.willInputCallback = ^{
                [JMCommonMethod uploadStatistics:@"EditBankcard" actionType:@"CLABE1_Focus" parameters:nil];
            };
            itemView.inputCallback = ^(NSDictionary * _Nonnull value) {
                NSString *result =  (NSString *)value;
                if (result != nil) {
                    weakSelf.userBanckInfoModel.bankCard = result;
                    
                    NSString * regex = @"^[0-9]{16}$|^[0-9]{18}";
                      
                    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
                    BOOL isMatch = [pred evaluateWithObject: result];
                    if (isMatch == NO) {
                        itemView.warningLab.superview.hidden = NO;
                        itemView.warningLab.text = @"*Por favor poner su núemro CLABE INTERBANCARIA como aparece en su Estado de Cuenta, asegurarse que sea de 18 dígitos. O poner su número de tarjeta bancaria como aparece en su tarjeta, asegurarse que sea de 16 dígitos.";
                        self.isBankCard = NO;
                    }else {
                        itemView.warningLab.superview.hidden = YES;
                        self.isBankCard = YES;
                    }
                    
                    if (self.bankCardConfirmView != nil) {
                        self.bankCardConfirmView.inputCallback(self.bankCardConfirmView.textField.text);
                    }
                }
                
                [weakSelf checkConfirmViewAble];
            };
            
        }
        else if (i == 2) {
            self.bankCardConfirmView = itemView;
            itemView.titleLab.text = @"Confirmar la cuenta CLABE o tarjeta bancaria";
            itemView.textField.placeholder = @"Por favor escribe";
            itemView.textField.enabled = YES;
            itemView.moreImage.hidden = YES;
            itemView.textField.keyboardType = UIKeyboardTypeNumberPad;
            itemView.textField.clearButtonMode = UITextFieldViewModeWhileEditing;

            itemView.textField.tag = 300;
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:itemView.textField];

            itemView.willInputCallback = ^{
                [JMCommonMethod uploadStatistics:@"EditBankcard" actionType:@"CLABE2_Focus" parameters:nil];
            };
            itemView.inputCallback = ^(NSDictionary * _Nonnull value) {
                NSString *result =  (NSString *)value;
                if (result != nil) {
                    
                    if (itemView.textField.text.length == 0) {
                        return;
                    }
                    BOOL isMatch = [result isEqualToString:self.userBanckInfoModel.bankCard];
                    if (isMatch == NO) {
                        itemView.warningLab.superview.hidden = NO;
                        itemView.warningLab.text = @"*El número de la cuenta bancaria no coincide";
                        self.isBankCardEqual = NO;
                    }else {
                        itemView.warningLab.superview.hidden = YES;
                        self.isBankCardEqual = YES;
                    }
                }
                [weakSelf checkConfirmViewAble];
            };
        }
        
        [self.scrollView.rootStack addContentView: [PaddingView initWithContentView:itemView edgeInsets:(UIEdgeInsetsMake(i == 0 ? 25 : 25, 0, 0, 0))]];
    }
}

#pragma mark - 校验确认按钮是否可用
- (void)checkConfirmViewAble {
    
    BOOL able = YES;
    if (self.userBanckInfoModel.bankCode == nil || self.userBanckInfoModel.bankCode.length == 0) {
        able = NO;
    }
    
    if (self.userBanckInfoModel.bankName == nil || self.userBanckInfoModel.bankName.length == 0) {
        able = NO;
    }
    
    
    if (self.userBanckInfoModel.bankCard == nil || self.userBanckInfoModel.bankCard.length == 0) {
        able = NO;
    }
    
    if (self.isBankCard == NO || self.isBankCardEqual == NO) {
        able = NO;
    }


    self.confirmView.confirmBut.enable = able;
}

//这里可以通过发送object消息获取注册时指定的UITextField对象
- (void)textFieldDidChangeValue:(NSNotification *)notification
{
    UITextField *sender = (UITextField *)[notification object];
    if(sender.tag==100){
        self.bankName = sender.text;
    }
    if(sender.tag==200){
        self.cardNum = sender.text;
    }
    if(sender.tag==300){
        self.cardNumConfirm = sender.text;
    }
    if(sender.tag==400){
        self.code = sender.text;
    }
    
    if(sender.tag==400){
        if(sender.text.length){
            self.popupView.confirmView.confirmBut.enable = YES;
        }else{
            self.popupView.confirmView.confirmBut.enable = NO;
        }
    }else{
        if(self.bankName.length && self.bankName.length && self.bankName.length){
                self.confirmView.confirmBut.enable = YES;
            }else{
                self.confirmView.confirmBut.enable = NO;
        }
    }
   
}


//获取验证码
-(void)loginBtnClick{

    NSDictionary *param;
    [self.confirmView.confirmBut startLoading];
    param =  @{@"phone":JMProjectManager.sharedJMProjectManager.loginUser.phone,@"type":@"modify_bank",@"voiceCode":@"false"};
    
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(loginSendSms) params:param success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [JMProgressHelper toastInWindowWithMessage:@"Código de verificación por SMS obtenido con éxito"];
        [self.confirmView.confirmBut endLoading];
        //验证码获取成功后弹出输入框
        [self pushPhoneAlert];
    } fail:^(NSString * _Nonnull errorMsg) {
        [JMProgressHelper toastInWindowWithMessage:errorMsg];
        [self.confirmView.confirmBut endLoading];
    }];
}

-(void)pushPhoneAlert{
    [self.popupView popup:[UIApplication sharedApplication].keyWindow edgeInsets:(UIEdgeInsetsZero)];
    self.popupView.warnLab.text = @" ";;

    dispatch_async(dispatch_get_main_queue(), ^{
       
        [self.popupView setRoundedCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) radii:30];
    });
}
#pragma mark - 点击事件
- (void)confirmAction:(UIButton *)sender {
    [self loginBtnClick];
   
}

#pragma mark - 懒加载
- (UIStackView *)rootStack {
    if (!_rootStack) {
        self.rootStack = [UIStackView new];
        _rootStack.alignment = UIStackViewAlignmentCenter;
        _rootStack.axis = UILayoutConstraintAxisVertical;
        _rootStack.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:_rootStack];
        [self.rootStack mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(@(NAVIGATION_BAR_HEIGHT()));
        }];
    }
    return  _rootStack;
}
- (LayoutScrollView *)scrollView {
    if (!_scrollView) {
        self.scrollView = [LayoutScrollView new];
        _scrollView.rootStack.contentView.axis = UILayoutConstraintAxisVertical;
        [_scrollView.widthAnchor constraintEqualToConstant: kScreenWidth].active = YES;
        _scrollView.rootStack.layoutViewAlignment = LayoutViewAlignmentTop;
        _scrollView.contentInset = UIEdgeInsetsMake(36, 0, 0, 0);
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.rootStack.layoutViewAlignment = LayoutViewAlignmentTop;
    }
    return _scrollView;
}

- (JMAuthentiactionConfirmView *)confirmView {
    if (!_confirmView) {
        self.confirmView = [JMAuthentiactionConfirmView new];
        _confirmView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _confirmView.confirmBut.enable = NO;
        [_confirmView.confirmBut addTarget:self action:@selector(confirmAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _confirmView;
}
- (JMUserBanckInfoModel *)userBanckInfoModel {
    if (!_userBanckInfoModel) {
        self.userBanckInfoModel = [JMUserBanckInfoModel new];
    }
    return _userBanckInfoModel;
}

- (JMPhoneCodePopupView *)popupView {
    if (!_popupView) {
        self.popupView = [JMPhoneCodePopupView new];
        self.popupView.textField.tag = 400;
        [self.popupView.confirmView.confirmBut addTarget:self action:@selector(modify) forControlEvents:(UIControlEventTouchUpInside)];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeValue:) name:UITextFieldTextDidChangeNotification object:_popupView.textField];
        [_popupView.widthAnchor constraintEqualToConstant:kScreenWidth].active = YES;
    }
    return _popupView;
}


-(void)modify{
    
    JMLoginUserModel *user = JMProjectManager.sharedJMProjectManager.loginUser;
    NSDictionary *param = @{
            @"data": @{@"bankCode":user.modBankCode?user.modBankCode:@"",@"bankName":self.userBanckInfoModel.bankName?:@"",@"bankCard":self.userBanckInfoModel.bankCard?:@""}.jsonStringEncoded,
            @"step": user.step?user.step:@"",
            @"vcode": self.popupView.textField.text?:@""
        };
    [self.popupView.confirmView.confirmBut startLoading];
    
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/auth/modify-bankcard") params:param success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        [JMProgressHelper hidenLoadingInWindow];

        [self.popupView.confirmView.confirmBut endLoading];
        [JMProgressHelper toastInWindowWithMessage:@"Su cuenta bancaria fue modificada con \néxito!"];
        
        [self.popupView dismissPopup];
        [self.navigationController popToRootViewControllerAnimated:YES];
        delayOperation(0.1, ^{
            [UIWindow.jm_currentViewController.rdv_tabBarController setSelectedIndex:0];
        });
        
        [JMCommonMethod uploadStatistics:@"EditBankcard" actionType:@"Save" parameters:nil];

    } fail:^(NSString * _Nonnull errorMsg) {
        [self.popupView.confirmView.confirmBut endLoading];
        self.popupView.warnLab.text = @"Error de código de verificación";;
        [JMProgressHelper toastInWindowWithMessage:errorMsg];
    }];
}

@end

